package www.golf.web.util;

import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import javax.imageio.ImageIO;

import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Image;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

public class UtilImage {
	Window win;
	public UtilImage(Window win){
		this.win=win;
	}
	public void setImage(String vboxId,String imageId,byte[] data,int pixelX_Show,int pixelY_Show){
		if(data!=null){
			Image image =new Image();
			imageEvent(image);
			image.setId(imageId);
			image.setHeight(pixelY_Show+"px");
	        image.setWidth(pixelX_Show+"px");
	        image.setParent(win.getFellow(vboxId));
	        InputStream buffin = new ByteArrayInputStream(data);
	
	        RenderedImage bi = null;
			try {
				bi = ImageIO.read(buffin);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.gc();
			image.setContent(bi);
        }
	}
	public void fileUploadUtil(String vboxId,String imageId,int uploadNumber,int pixelX_Show,int pixelY_Show,int pixelX_Static,int pixelY_Static){
		try {
			Fileupload fileUpload=new Fileupload();
			Media[] media = fileUpload.get(uploadNumber);
			if (media != null)
			for (int j = 0; j < (media).length; ++j) {
	            if (media[j] instanceof org.zkoss.image.Image &&media[j].getByteData().length<3145728) {
	            	Image image=null;
	            	try{
	            		image = (Image) win.getFellow(imageId+j);
	            	}catch(Exception e){
	            		image = new Image();
	            		imageEvent(image);
	            		image.setId(imageId+j);
	            		win.getFellow(vboxId).appendChild(image);
	            	}
	                image.setHeight(String.valueOf(pixelY_Show)+"px");
	                image.setWidth(String.valueOf(pixelX_Show)+"px");
	                HashMap map=getScaleXY(media[j].getByteData(),pixelX_Static,pixelY_Static);
	                try {
	                	 image.setContent(convert((Integer)map.get("x"), (Integer)map.get("y"), (BufferedImage)map.get("bufferedImage")));
					} catch (Exception e) {
						e.printStackTrace();
					}
	            } else if (media[j] != null) {
						Messagebox.show("請統一上傳圖片,且單張圖片不得超過4MB", "Error",
						Messagebox.OK, Messagebox.ERROR);
	            }
			}
		} catch (InterruptedException e) {
				e.printStackTrace();
		}
	}
	/**
	 * 指定image開出
	 * @param image
	 * @param win
	 */
	public void imageEvent(Image image){
		image.addEventListener("onClick", new EventListener(){

			public void onEvent(Event event) throws Exception {
				Image image=(Image) event.getTarget();
				Image imgCopy=(Image) image.clone();
				imgCopy.setHeight("");
				imgCopy.setWidth("");
				Window win = new Window();
				win.appendChild(imgCopy);
				win.setWidth(String.valueOf(imgCopy.getContent().getWidth()+20));
				setWin(win);
			}
			
		});
	}
	/**
	 * 指定image開出的win或是panel
	 * @param image
	 * @param win
	 */
	public void imageEvent(Image image,final Window win){
		image.addEventListener("onClick", new EventListener(){

			public void onEvent(Event event) throws Exception {
				Image image=(Image) event.getTarget();
				Image imgCopy=(Image) image.clone();
				imgCopy.setHeight("");
				imgCopy.setWidth("");
				win.appendChild(imgCopy);
				win.setWidth(String.valueOf(imgCopy.getContent().getWidth()+20));
				setWin(win);
			}
			
		});
	}
	/**
	 * 取image byte data 轉換成MAP 資料,MAP資料如return.<P>
	 * 此為配合UtilImage.convert()可以轉換image大小
	 * @param data 資料串流
	 * @param limitX 欲轉換X值,會依據Y值scale
	 * @param limitY 欲轉換Y值,會依據X值scale
	 * @return HashMap<p>
	 * <pre>
	 * key->"bufferedImage", value->BufferedImage<p>
	 * key->"x", value->int<p>
	 * key->"y", value->int<p>
	 * </pre>
	 */
	public HashMap<String, Object> getScaleXY(byte[] data,int limitX ,int limitY){
		int x=0,y=0;
		double scaleX=0,scaleY=0;
		HashMap<String, Object> map= new HashMap<String, Object>();
		InputStream buffin = new ByteArrayInputStream(data);
		BufferedImage image = null;
		try {
			image = ImageIO.read(buffin);
		} catch (IOException e) {
			e.printStackTrace();
		}
		x=image.getWidth();
		y=image.getHeight();
		scaleX=image.getWidth()/limitX;scaleY=image.getHeight()/limitY;
		if(scaleX>=scaleY&&x>limitX&&y>limitY){
			int tempH= (int) (image.getHeight()/scaleX);
			int tempW= (int) (image.getWidth()/scaleX);
			map.put("x",tempW);
			map.put("y",tempH);
		}else if(scaleX<scaleY&&x>limitX&&y>limitY){
			int tempH= (int) (image.getHeight()/scaleY);
			int tempW= (int) (image.getWidth()/scaleY);
			map.put("x",tempW);
			map.put("y",tempH);
		}else{
			map.put("x",x);
			map.put("y",y);
		}
		map.put("bufferedImage", image);
		return map;
	}
	/**
	 * 轉換image buffer輸出
	 * @param width 轉換的X值
	 * @param height 轉換的Y值
	 * @param input BufferedImage
	 * @return BufferedImage
	 * @throws Exception
	 */
	public BufferedImage convert(int width, int height,BufferedImage input) throws Exception {
		BufferedImage output = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
		java.awt.Image image = input.getScaledInstance(output.getWidth(), output.getHeight(), output.getType());
		output.createGraphics().drawImage(image,null,null);
		return output;
	}
	public void setWin(Window win){
		try {
	   	    win.setLeft("200");
	   	    win.setTop("200");
	   	    win.setClosable(true);
			win.doModal();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
